
"use strict";

//外部接口
var sku = {
        config:{}
        //  设置全局配置项
        ,set:function (options) {
            var that = this;
            that.config = $.extend({}, that.config, options);
        }
    }
    //字符常量
    ,MOD_NAME = 'sku'
    //  构造器
    ,Class = function (options) {
        let that = this;

        that.config = $.extend({}, that.config, sku.config, options);

        that.render();
    };
    //  默认配置
    Class.prototype.config = {
        attr_length:3,  //  规格最多长度
        attr_values_length:3,    //  规格值最多多少项
        default_table_header: ["进货价","库存","卖出价格","会员价格"],    //  默认表格头部
        sku:[], //  sku规格
        sku_items:[],   //  sku每条
        is_debug:true,   //  是否调试模式，调试模式显示获得数据按钮，可在页面点击后 console.log 看到
    };

    //  临时数据
    Class.prototype.temp = {
        tableHeader :[] //  临时表头组合存放
    }

    //  渲染表头
    Class.prototype.renderTableHeader = function () {

        var that = this, tableHeader = [];

        $("#tableHeader").empty();

        that.config.sku.map(function (item) {
            if (item.attr_values.length > 0){
                tableHeader.push(item.attr);
            }
        })

        that.temp.tableHeader = tableHeader.concat(that.config.default_table_header);

        var html = '';
        for (var i = 0; i < that.temp.tableHeader.length; i++){
            html += "<td>"+ that.temp.tableHeader[i] +"</td>"
        }

        $("#tableHeader").append(html);
    };

    //  渲染表格内容
    Class.prototype.renderTableBody = function () {

        var  arr1 = []
            ,arr2 = []
            ,sku = this.config.sku
            ,that = this;

        if (sku.length === 0){
            that.config.sku_items = [];

            $("#table tr").map(function (item,index) {

                if (item != 0){
                    $(this).remove();
                }
            });

            return;
        }

        //  移除表头外的东西. 第一个tr不动
        $("#table tr").map(function (item,index) {

            if (item != 0){
                $(this).remove();
            }
        });

        if (sku.length === 1){

            var zz =[];

            var attr_values = sku[0].attr_values;

            var html = "";

            //组合的表头长度
            var m = that.temp.tableHeader.length;

            attr_values.forEach(function (item,index) {

                var u  = [item];

                var e = [];

                html += "<tr>";
                html += "<td>"+ item +"</td>";

                var i = that.config.default_table_header.length;

                while (i >= 0){
                    var val = [0];

                    if (that.config.sku_items[index] != undefined  && that.config.sku_items[index][m-i] ){
                        val = [that.config.sku_items[index][m-i]];
                    }

                    // 判断是否是最后一个，如果是最后一个就隐藏了！
                    if ( i != 0 ){
                        html += "<td>" + "<input type='text' value='"+ val +"' class='change-item-value' i='"+ index +"' j='"+ (m - i) +"'>";
                    }else {
                        html += "<td style='display: none'>" + "<input type='text' value='"+ val +"' class='change-item-value' i='"+ index +"' j='"+ (m - i) +"'>";
                    }

                    e = e.concat(val);
                    i--;
                }


                html += "<tr/>";
                var uu = u.concat(e);

                zz.push(uu);

            });

            that.config.sku_items = zz;

            $("#table").append(html);

        }else {

            var attr_value_cumb = [];

            sku.forEach(function ($item) {
                attr_value_cumb.push($item.attr_values);
            });

            var result = attr_value_cumb.shift();

            while (arr2 = attr_value_cumb.shift()){

                if (arr2 != undefined){
                    arr1 = result;

                    result = [];

                    arr1.forEach(function (key) {
                        arr2.forEach(function (kkey){
                            if (!Array.isArray(key)){
                                key = [key];
                            }

                            if (!Array.isArray(kkey)){
                                kkey = [kkey];
                            }

                            var ee = [];
                            ee = (ee.concat(kkey).concat(key)).reverse();

                            result.push(ee);
                        });
                    })
                }
            }
            //  组合body数据，为了防止在上面双层循环中在套循环看着难受，拿出来写

            var html = "";
            var temp = result;
            var m = that.temp.tableHeader.length;

            result.forEach(function (item,index) {
                html += "<tr>";

                item.forEach(function (iitem) {
                    html += "<td>"+ iitem +"</td>"
                });

                var i = that.config.default_table_header.length;

                while (i >= 0){
                    var val = 0;

                    if (that.config.sku_items[index] != undefined  && that.config.sku_items[index][m-i] ){
                        val = that.config.sku_items[index][m-i];
                    }

                    if (i != 0){
                        html += "<td>" + "<input type='text' value='"+ val +"' class='change-item-value' i='"+ index +"' j='"+ (m - i) +"'>";
                    }else {
                        html += "<td style='display: none'>" + "<input type='text' value='"+ val +"' class='change-item-value' i='"+ index +"' j='"+ (m - i) +"'>";
                    }

                    temp[index].push(val);
                    i--;
                }
                html += "<tr/>";
            });


            that.config.sku_items = temp;

            $("#table").append(html);
        }
    };

    //  渲染可添加规格输入框
    Class.prototype.renderInputAttr = function () {

        var sku = this.config.sku,html = "<div>";

        $('.items').empty();

        for (var i = 0; i < sku.length; i++){

            html += "<div>"+ sku[i].attr +"</div>"

            html += "<div style='display: inline-block'>";

            for (var j = 0; j < sku[i].attr_values.length; j++){
                html += "<input i='"+ i+"' j='"+ j +"' class='change-items'   value='"+ sku[i].attr_values[j] +"'  placeholder='请输入规格值' style='display:inline-block;float:left  ' type='text'>";

                html += "<span class='btn ' i='"+ i+"' j='"+ j +"' onclick='sku.delAttrValue("+ i + "," + j+")' style='display: inline-block;float: left'>删除</span>"
            }

            html += "<input type='text' class='item"+ i +"' value='' placeholder='请输入规格值'  style='display:inline-block;float: left '>";

            html += "<span class='btn add-item' i='"+ i +"' onclick='sku.addAttrValue("+ i +")'>添加`</span>";
            html += "<span class='btn del-items' i='"+ i +"' onclick='sku.delAttrValues("+ i +")'>删除整行1</span>";
            html += "</div>";
        }

        html += "</div>";
        $(".items").append(html);
    };

    //  渲染
    Class.prototype.render = function () {

        //  是否开启调试模式
        if (this.config.is_debug){
            $('.none').show();
        }

        this.renderTableHeader();
        this.renderInputAttr();
        this.renderTableBody();
    };


    //  删除规格值
    Class.prototype.delAttrValue = function (i,j) {

        console.log(i);
        console.log(j);
        console.log(this.config.sku);
        this.config.sku[i].attr_values.splice(j,1);

        this.render();
    }

    //删除整行规格值
    Class.prototype.delAttrValues = function (i) {


        this.config.sku.splice(i,1);

        this.render();
    }


    //  获得提交数据
    Class.prototype.get = function () {

    };

    //  测试
    Class.prototype.test = function () {
        alert(1);
    }

    //添加规格
    Class.prototype.addAttr = function () {
        var that = this, attr = $("#attr").val();

        if (attr === ''){
            alert('请输入规格'); return;
        }

        if (that.config.sku.length >= that.config.attr_length){
            alert('最多输入'+ that.config.attr_length +'个规格'); return;
        }

        if ( that.config.sku.length >= 1 ){

            for (var i = 0; i < that.config.sku.length; i++){

                if (that.config.sku[i].attr == attr){
                    alert('规格已存在');
                    return;
                }
            }
        }

        that.config.sku.push({
            attr: attr,
            attr_values :[],
            id:that.id()
        });

        that.render();

        $("#attr").val('');
    }

    //  添加规格值
    Class.prototype.addAttrValue = function (i) {

        var item = '.item' + i;

        if ($(item).val() == ''){
            alert('请输入规格值');
            return;
        }

        if (this.config.sku[i].attr_values.length >= this.config.attr_values_length){
            alert('最多输入' + this.config.attr_values_length + '个规格值');
            return;
        }

        this.config.sku[i].attr_values.push($(item).val());

        this.render();
    }

    //  生成假的随机id
    Class.prototype.id = function () {
        const timestamp = +new Date() + '';
        const randomNum = parseInt((1 + Math.random()) * 65536) + '';
        return (+(randomNum + timestamp)).toString(32);
    }

    Class.prototype.setSku = function (sku) {
        this.config.sku = sku;

        this.render();
    }

    Class.prototype.setSkuItems = function (skuItems) {
        this.config.sku_items = skuItems;

        this.render();
    }

    //  当规格值改变的时候，
    $(document).on('input propertychange','.change-item-value',function () {

        var i = $(this).attr('i');
        var j = $(this).attr('j');

        sku.config.sku_items[i][j] = $(this).val();
    });

    //  当规格改变的时候
    $(document).on('input propertychange','.change-items',function () {

        var i = $(this).attr('i');
        var j = $(this).attr('j');
        sku.config.sku[i].attr_values[j] = $(this).val();

        sku.render();
    });

    $(function () {
        $('.get').click(function () {
            console.log(sku.config.sku);
            console.log(sku.config.sku_items);
        })
    })
